/**
 * 
 */
package wikiextract.nlp.trainingset.x;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import wikiextract.data.util.StringUtil;

public class FeaturesRecord {
	public int attributesNamesId;
	public int articleId;
	public int sentenceId;
	public boolean useForLearning;
	public String[] tokens;
	public byte[][] matchPos;
	public byte[] matchLabels;
	public List<Integer>[] features;
	public boolean EOF = false;
	
	public boolean read(DataInput in) throws IOException {
		try {
			attributesNamesId = in.readInt();
			articleId = in.readInt();
			sentenceId = in.readInt();
			useForLearning = in.readBoolean();
			int len = in.readInt();
			String t = in.readUTF();
			tokens = StringUtil.split(t, ' ', len);
			byte num = in.readByte();
			matchPos = new byte[num][2];
			matchLabels = new byte[num];
			for (int i=0; i < num; i++) {
				matchPos[i][0] = in.readByte();
				matchPos[i][1] = in.readByte();
				matchLabels[i] = in.readByte();
			}
			//labels = new boolean[len];
			//for (int i=0; i < len; i++) 
			//		labels[i] = in.readBoolean();
			features = new ArrayList[len];
			for (int l=0; l < features.length; l++) {
				features[l] = new ArrayList<Integer>();
				int llen = in.readInt();
				for (int i=0; i < llen; i++) features[l].add(in.readInt());
			}
			return true;
		} catch (EOFException e) {
			EOF = true;
			return false; 
		}
	}
	
	public void write(DataOutput out) throws IOException {
		if (tokens.length != features.length)
			throw new IOException("length mismatch: "  + tokens.length + " != " + features.length);				 
		out.writeInt(attributesNamesId);
		out.writeInt(articleId);
		out.writeInt(sentenceId);
		out.writeBoolean(useForLearning);
		out.writeInt(features.length);
		StringBuilder sb = new StringBuilder();
		for (int i=0; i < tokens.length; i++) {
			if (i > 0) sb.append(" ");
			sb.append(tokens[i]);
		}
		out.writeUTF(sb.toString());
		out.writeByte(matchPos.length);
		for (int i=0; i < matchPos.length; i++) {
			out.writeByte(matchPos[i][0]);
			out.writeByte(matchPos[i][1]);
			out.writeByte(matchLabels[i]);
		}

		//for (int i=0; i < labels.length; i++)
		//	out.writeBoolean(labels[i]);
		for (List<Integer> l : features) {
			out.writeInt(l.size());
			for (Integer i : l) out.writeInt(i);
		}
	}
	
	public FeaturesRecord clone() {
		// warning: does not clone features
		FeaturesRecord o = new FeaturesRecord();
		o.attributesNamesId = attributesNamesId;
		o.articleId = articleId;
		o.sentenceId = sentenceId;
		o.useForLearning = useForLearning;
		o.tokens = tokens;
		o.matchPos = matchPos;
		o.matchLabels = matchLabels;
		o.features = features;
		return o;
	}
}